package com.kpmg.datalake.web.filter;

import com.kpmg.datalake.common.dynamicdatasource.DynamicDataSourceContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.util.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Locale;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-07-19 18:11:09
 */
public class CookieFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        //do nothing

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpSession session = httpRequest.getSession();
        httpResponse.setHeader("jsId", session.getId());
        httpResponse.setContentType("text/html;charset=utf-8");
        String acceptLang = httpRequest.getHeader("acceptLang");
        if (StringUtils.isNotBlank(acceptLang)) {
            WebUtils.setSessionAttribute(httpRequest, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale(acceptLang));
        }
        DynamicDataSourceContextHolder.clearDataSource();
        chain.doFilter(httpRequest, httpResponse);
    }

    @Override
    public void destroy() {
        //do nothing
    }
}
